using System;
using Microsoft.SPOT;
using Netduino4Fun.DesktopAssistant.Netduino.Communication;
using Netduino4Fun.Framework.Log;
using System.Text;
using System.Threading;

namespace Netduino4Fun.DesktopAssistant.Netduino
{
    public class DesktopAssistant
    {
        Connection connection;
        Log log;

        RgbLed led = new RgbLed();


        public DesktopAssistant(Connection connection, Log log)
        {
            this.connection = connection;
            this.log = log;
        }

        public void Start()
        {
            connection.LineReceived += new LineReceivedEventHandler(HandlerRequest);
            connection.Open();

            Thread.Sleep(Timeout.Infinite);
        }

        private void HandlerRequest(string request)
        {
            log.Write("Request : " + request);

            string response = ExecuteRequest(request);

            log.Write("Response : " + response);
            connection.WriteLine(response);
        }

        private string ExecuteRequest(string request)
        {
            string command;
            string[] arguments;
            ParseRequest(request, out command, out arguments);

            string result = null;
            switch (command)
            {
                case "ChangeColor":
                    int red = 0, green = 0, blue = 0;
                    try
                    {
                        red = int.Parse(arguments[0]);
                        green = int.Parse(arguments[1]);
                        blue = int.Parse(arguments[2]);
                    }
                    catch (Exception e)
                    {
                        log.Write(e.Message);
                    }

                    led.ChangeColor(red, green, blue);
                    break;
                default:
                    break;
            }
            return result;
        }

        private void ParseRequest(string request, out string command, out string[] parameters)
        {
            command = null;
            parameters = null;

            string[] split = request.Split(' ');

            if (split.Length < 1)
                return;
            command = split[0];

            if (split.Length < 2)
                return;
            parameters = new string[split.Length - 1];
            for (int i = 0; i < parameters.Length; i++)
                parameters[i] = split[i + 1];
        }
    }
}
